package com.ja.openchat.viewmodels;

import android.app.Application;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import com.google.gson.JsonObject;
import com.ja.openchat.ui.chat.ChatActivity;
import com.ja.openchat.ui.me.AboutFragment;
import com.ja.openchat.ui.me.AccountSecurityActivity;
import com.ja.openchat.ui.me.LatestCallActivity;
import com.ja.openchat.ui.me.MyAlbumFragment;
import com.ja.openchat.ui.me.PaymentReceivedCodeFragment;
import com.ja.openchat.ui.me.PeopleNearbyViewPagerGroupFragment;
import com.ja.openchat.ui.me.PersonalDataFragment;
import com.ja.openchat.ui.me.QrCodeFragment;
import com.ja.openchat.ui.me.RechargeFragment;
import com.ja.openchat.ui.me.SetFragment;
import com.ja.openchat.ui.me.WalletFragment;
import com.ja.openchat.ui.me.WithdrawalFragment;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgEvent;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.core.model.wallet.WalletInfo;
import com.zy.openchat.util.Common;

import org.apache.commons.lang3.StringUtils;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.util.HashMap;
import java.util.Map;

import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;


public class MeViewModel extends BaseViewModel {
    //用户名的绑定
    public ObservableField<String> userName = new ObservableField<>(UserInfo.getUserInfo().displayName());
    public ObservableField<String> walletValue = new ObservableField<>("¥0.00");
    public ObservableField<UserInfo> userAvatar = new ObservableField<>(UserInfo.getUserInfo());
    //二级用户名的绑定
    public ObservableField<String> userNameSub = new ObservableField<>(StringUtils.isEmpty(UserInfo.getUserInfo().username) ? "" : ("@" + UserInfo.getUserInfo().username));
    public ObservableField<String> userPhone = new ObservableField<>(Common.formatPhoneNumber(UserInfo.getUserInfo().phone_number));

    public UIChangeLiveData mUC = new UIChangeLiveData();

    public MeViewModel(@NonNull @NotNull Application application) {
        super(application);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
    public final class UIChangeLiveData extends SingleLiveEvent {
        private SingleLiveEvent<Map<String, Object>> showLongClickDialogEvent;

        public SingleLiveEvent<Map<String, Object>> getShowPaymentPasswordDialogEvent() {
            return showLongClickDialogEvent = new SingleLiveEvent<>();
        }
    }

    //账号与安全点击事件
    public BindingCommand accountSecurityOnClickCommand = new BindingCommand(() -> {
        startActivity(AccountSecurityActivity.class);
    });

    //长按昵称事件
    public BindingCommand nickOnLongClickCommand = new BindingCommand(() -> {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("content", userName.get());
        hashMap.put("type", 1);
        mUC.showLongClickDialogEvent.setValue(hashMap);
    });
    //长按用户名事件
    public BindingCommand nameOnLongClickCommand = new BindingCommand(() -> {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("content", userNameSub.get());
        hashMap.put("type", 2);
        mUC.showLongClickDialogEvent.setValue(hashMap);
    });
    //长按手机号事件
    public BindingCommand phoneOnLongClickCommand = new BindingCommand(() -> {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("content", userPhone.get());
        hashMap.put("type", 3);
        mUC.showLongClickDialogEvent.setValue(hashMap);
    });
    //登录按钮的点击事件
    public BindingCommand loginOnClickCommand = new BindingCommand(() -> {
    });
    //关于我们按钮的点击事件
    public BindingCommand aboutOnClickCommand = new BindingCommand(() -> startContainerActivity(AboutFragment.class.getCanonicalName()));

    //设置按钮的点击事件
    public BindingCommand setOnClickCommand = new BindingCommand(() -> startContainerActivity(SetFragment.class.getCanonicalName()));

    //个人资料点击事件
    public BindingCommand personalDataOnClickCommand = new BindingCommand(() -> {
        startContainerActivity(PersonalDataFragment.class.getCanonicalName());
    });
    //钱包点击事件
    public BindingCommand walletOnClickCommand = new BindingCommand(() -> {
        startContainerActivity(WalletFragment.class.getCanonicalName());
    });
    //我的二维码点击事件
    public BindingCommand qrCodeOnClickCommand = new BindingCommand(() -> {
        startContainerActivity(QrCodeFragment.class.getCanonicalName());
    });
    //提现点击事件
    public BindingCommand withdrawalOnClickCommand = new BindingCommand(() -> {
        startContainerActivity(WithdrawalFragment.class.getCanonicalName());
    });
    //提现点击事件
    public BindingCommand rechargeOnClickCommand = new BindingCommand(() -> {
        startContainerActivity(RechargeFragment.class.getCanonicalName());
    });
    //收付款二维码点击事件
    public BindingCommand paymentReceivedCodeOnClickCommand = new BindingCommand(() -> {
        startContainerActivity(PaymentReceivedCodeFragment.class.getCanonicalName());
    });
    //附近的人点击事件
    public BindingCommand nearbyOnClickCommand = new BindingCommand(() -> {
        Bundle bundle = new Bundle();
        bundle.putInt("type", 1);
        startContainerActivity(PeopleNearbyViewPagerGroupFragment.class.getCanonicalName(), bundle);
    });
    //公开的群点击事件
    public BindingCommand openGroupClickCommand = new BindingCommand(() -> {
        Bundle bundle = new Bundle();
        bundle.putInt("type", 2);
        startContainerActivity(PeopleNearbyViewPagerGroupFragment.class.getCanonicalName(), bundle);
    });
    //邀请好友点击事件
    public BindingCommand inviteOnClickCommand = new BindingCommand(() -> {

    });
    //我的相册点击事件
    public BindingCommand myAlbumOnClickCommand = new BindingCommand(() -> {
        startContainerActivity(MyAlbumFragment.class.getCanonicalName());
    });
    //最近通话点击事件
    public BindingCommand latestCallOnClickCommand = new BindingCommand(() -> {
        startActivity(LatestCallActivity.class);
    });
    //客服点击事件
    public BindingCommand kefuOnClickCommand = new BindingCommand(() -> {
        requestUserService();
    });
    //我的收藏点击事件
    public BindingCommand fovCallOnClickCommand = new BindingCommand(() -> {
        TelegramManager.getTelegramManager().createPrivateChat(getApplication(), UserInfo.getUserInfo().id, new TgResultBlock<ChatInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, ChatInfo obj) {
                if (obj != null) {
                    Bundle bundle = new Bundle();
                    bundle.putParcelable("conversation", obj);
                    startActivity(ChatActivity.class, bundle);
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
            }
        });
    });

    //跳转在线客服
    private void requestUserService() {
        showProgress();
        TelegramManager.getTelegramManager().getOnlineUserService(getApplication(), new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (obj.ok) {
                    long id = (long) obj.data;
                    if (TelegramManager.getTelegramManager().getTgData().contactInfo(id) != null) {
                        showProgress();
                        toPrivateChat(id);
                    } else {
                        showProgress();
                        TelegramManager.getTelegramManager().requestContactInfo(getApplication(), id, new TgResultBlock<UserInfo>() {
                            @Override
                            public void onResult(Map<String, Object> request, JsonObject response, UserInfo obj) {
                                toPrivateChat(id);
                            }

                            @Override
                            public void onTimeout(Map<String, Object> request) {
                                hideProgress();
                                showErrorTip("请求超时，请稍后重试");
                            }
                        });
                    }
                } else {
                    showErrorTip("获取客服信息失败，请稍后重试");
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip("获取客服信息失败，请稍后重试");
            }
        });
    }

    private void toPrivateChat(long userId) {
        TelegramManager.getTelegramManager().createPrivateChat(getApplication(), userId, new TgResultBlock<ChatInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, ChatInfo obj) {
                hideProgress();
                if (obj != null) {
                    Bundle bundle = new Bundle();
                    bundle.putParcelable("conversation", obj);
                    startActivity(ChatActivity.class, bundle);
                } else {
                    showErrorTip("请求错误，请稍后重试");
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip("请求超时，请稍后重试");
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTgEvent(final TgEvent tg_event) {
        switch (tg_event.event) {
            case EUser_Td_UpdateUserInfo: {
                resetUI();
            }
            break;
            case EUser_Td_Contact_Photo_Ok: {
                UserInfo user = (UserInfo) tg_event.data;
                if (user.id == UserInfo.getUserInfo().id) {
                    resetUI();
                }
            }
            break;
        }
    }

    private void resetUI() {
        UserInfo user = UserInfo.getUserInfo();
        userAvatar.set(user);
        userAvatar.notifyChange();
        userName.set(user.displayName());
        String userName = "";
        if (!StringUtils.isEmpty(user.username)) {
            userName = "@" + user.username;
        }
//        phoneText.setText(Common.formatPhoneNumber(user.phone_number));
        userNameSub.set(userName);
    }

    public void requestWalletInfo(){
        TelegramManager.getTelegramManager().queryWalletInfo(getApplication(), new TgResultBlock<WalletInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, WalletInfo walletInfo) {
                if(walletInfo!=null){
                    walletValue.set(String.format("¥%.2f",walletInfo.balance));
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {

            }
        });
    }
}
